package org.example.controller;

import jakarta.validation.constraints.NotEmpty;
import org.example.anno.State;
import org.example.pojo.Couplename;
import org.example.pojo.LoveDiary;
import org.example.service.CouplenameService;
import org.example.service.LoveDiaryService;
import org.example.utils.AilOssUtil;
import org.example.utils.Result;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/LoveDiary")
@Validated
public class LoveDiaryController {

    @Autowired
    private LoveDiaryService loveDiaryService;

    @Autowired
    private CouplenameService couplenameService;

    //添加恋爱日记(除照片外所有内容)
    @PostMapping("/add")
    public Result add(@NotEmpty String title, @NotEmpty String content, @Validated String mood) {
        //拿到用户个人id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        //通过个人id拿到绑定数据
        Couplename couplename = couplenameService.CoupleFindById(id);

        Integer userId = couplename.getId();

        loveDiaryService.add(title, content, mood, userId, null);

        return Result.success("添加成功！");

    }


    //恋爱日记列表
    @GetMapping("/list")
    public Result<List<LoveDiary>> list() {
        //拿到用户个人id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        //通过个人id拿到绑定数据
        Couplename couplename = couplenameService.CoupleFindById(id);

        Integer userId = couplename.getId();

        List<LoveDiary> loveDiary = loveDiaryService.list(userId);

        return Result.success(loveDiary);
    }

    //添加恋爱日记照片
    @PutMapping("/addphoto")
    public Result addphoto(MultipartFile file) throws Exception {
        //把文件上传到本地磁盘
        String originalFilename = file.getOriginalFilename();
        //保证文件名唯一，防止文件覆盖
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //添加阿里云oss存储
        String url = AilOssUtil.uploadFile(filename, file.getInputStream());

        return Result.success(url);

    }

    //恋爱日记的修改
    @PutMapping("/editLaveDiary")
    public Result editLaveDiary(String id, String title, String content, @Validated String mood) {

        loveDiaryService.editLaveDiary(id, title, content, mood, null);

        return Result.success("修改成功！");
    }

    //恋爱日记的删除
    @DeleteMapping("/deleteLaveDiary")
    public Result deleteLaveDiary(String id) {
        loveDiaryService.delete(id);
        return Result.success("日记删除成功");
    }

}
